package com.xingxing.Dao;

import com.xingxing.Bean.Likes;
import com.xingxing.Util.C3P0Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

public class LikesDao {
    public static boolean insert(Likes likes) {
        int num = 0;
        Connection conn = null;
        try {
            conn = C3P0Util.getConnection();
            QueryRunner runner = new QueryRunner();
            String sql = "insert into Likes values(?,?);";
            num = runner.update(conn, sql, new Object[]{
                    likes.getVideoID(),
                    likes.getUserAccount()
            });
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (num > 0) return true;
        return false;
    }

    public static ArrayList<Likes> findAll() {
        ArrayList list = null;
        try {
            QueryRunner runner = new QueryRunner();
            String sql = "select * from Likes";
            list = (ArrayList) runner.query(C3P0Util.getConnection(), sql, new BeanListHandler(Likes.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static ArrayList<Likes> findByVideoID(String videoID) {
        ArrayList list = null;
        try {
            QueryRunner runner = new QueryRunner();
            String sql = "select * from Likes where videoID=?";
            list = (ArrayList) runner.query(C3P0Util.getConnection(), sql, new BeanListHandler(Likes.class), new Object[]{videoID});
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static ArrayList<Likes> findByInSet(String[] videoID) {
        ArrayList list = null;
        try {
            QueryRunner runner = new QueryRunner();
            String sql = "select distinct * from Likes where videoID in ("+videoID[0];
            for (int i = 1; i < videoID.length; i++) {
                sql = sql + ","+videoID[i];
            }
            sql = sql +")";
            list = (ArrayList) runner.query(C3P0Util.getConnection(), sql, new BeanListHandler(Likes.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static boolean delete(Likes likes) {
        try {
            QueryRunner runner = new QueryRunner(C3P0Util.getDataSource());
            String sql = "delete from Likes where videoID = ? and userAccount=?";
            if (runner.update(sql, new Object[]{likes.getVideoID(), likes.getUserAccount()}) > 0) return true;
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
